import { Flex, Select, Table } from "antd"
import { styled } from '@umijs/max'
import StationSelect from "@/components/StationSelect"
import { CouponUseRange } from "@/constants/enums/coupon"

const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
`

type Value = {
  stationType?: CouponUseRange
  stationIds?: StationSelecter.Value[]
}

interface UseRangeProps {
  value?: Value
  onChange?: (value?: Value) => void
  style?: React.CSSProperties
}

export const rangeValidator = (value: any) => {
  if (!value.stationType) {
    return Promise.reject(new Error('请选择使用范围'))
  }
  if (value.stationType === 6 && value.stationIds?.length < 1) {
    return Promise.reject(new Error('请选择可用场站'))
  }
  return Promise.resolve()
}

const UseRange: React.FC<UseRangeProps> = props => {
  const del = (id: string) => {
    props.onChange?.({
      stationType: props.value?.stationType,
      stationIds: props.value?.stationIds?.filter(it => it.id !== id)
    })
  }

  return (
    <Container style={props.style}>
      <Flex align="center" style={{height: 32}}>
        <Select
          value={props.value?.stationType}
          style={{width: 320}}
          placeholder='请选择'
          allowClear={false}
          options={[
            {label: '全部场站', value: CouponUseRange.全部场站},
            // {label: '企业全部场站', value: CouponUseRange.企业全部场站},
            {label: '所有自营场站', value: CouponUseRange.所有自营场站},
            {label: '所有联营场站', value: CouponUseRange.所有联营场站},
            // {label: '所有会员站', value: CouponUseRange.所有会员站},
            {label: '指定场站', value: CouponUseRange.指定场站},
          ]}
          onChange={(val) => props.onChange?.({...props.value, stationType: val})}
        />
      </Flex>
      {
        props.value?.stationType === 6 && [
          <StationSelect
            key='chose'
            type="checkbox"
            value={props.value?.stationIds}
            onChange={(val) => props.onChange?.({...props.value, stationIds: val})}
          />,
          <Table
            key='table'
            rowKey='id'
            columns={[
              {title: '场站名称', dataIndex: 'name'},
              {title: '操作', width: 100, dataIndex: 'id', render: (id) => {
                return <a onClick={() => del(id)}>删除</a>
              }},
            ]}
            dataSource={props.value?.stationIds}
            pagination={{
              pageSize: 10, total: props.value?.stationIds?.length || 0,
              size: 'small', simple: true, hideOnSinglePage: true,
            }}
          />
        ]
      }
    </Container>
  )
}

export default UseRange